#include "QDeleteNotebookView.h"
#include "QNotebookListItemWidget.h"
#include "QvernoteView.h"
#include "QNotebookListItemModel.h"
#include "MeegoSupport.h"

QDeleteNotebookView::QDeleteNotebookView(MApplicationPage *parent)
    : QvernoteWindow(parent->applicationWindow()),  m_hEvernote(QvernoteAPI::Instance()), m_iSelectedCount(0), m_parent(parent)
{
	ui.setupUi(this);
        setTitle(trUtf8("Delete notebooks"));
        //QObject::connect(ui.lwNotebookList, SIGNAL(itemClicked(const QModelIndex &)), this, SLOT(setItemMark(const QModelIndex &)));
        QObject::connect(ui.lwNotebookList, SIGNAL(itemLongTapped(const QModelIndex &)), this, SLOT(setItemMark(const QModelIndex &)));
	setProgressIndicator(true);
}

QDeleteNotebookView::~QDeleteNotebookView()
{

}

void QDeleteNotebookView::loadNotebooksIntoView()
{
	ui.lwNotebookList->setItemModel(new QNotebookListItemModel() );

	connect(((QNotebookListItemModel*)ui.lwNotebookList->itemModel()), SIGNAL(notebookMarked()), this, SLOT(addSelectedCount()));
	connect(((QNotebookListItemModel*)ui.lwNotebookList->itemModel()), SIGNAL(notebookUnmarked()), this, SLOT(subSelectedCount()));

	setProgressIndicator(false);
}

void QDeleteNotebookView::setItemMark(const QModelIndex& index)
{
    ((QNotebookListItemModel*)ui.lwNotebookList->itemModel())->toggleMark(index);
    ui.lwNotebookList->selectItem(index);
}

void QDeleteNotebookView::deleteSelectedNotebooks()
{
	QNotebookListItemWidget* currItem;
	QListWidgetItem* listWidgetItem;

	if(m_iSelectedCount == 0 ||
			MeegoSupport::MessageBox(trUtf8("Confirm"),
    		   QString(trUtf8("Ready to delete %1 notebooks?")).arg(m_iSelectedCount),
    		   M::YesButton|M::NoButton) == M::NoButton)
		return;

	ui.deleteSelectedAction->setEnabled(false);

	setProgressIndicator(true);
	for(int i = 0; i < ui.lwNotebookList->itemModel()->rowCount(); i++)
	{
		QModelIndex nextRowIndex = ui.lwNotebookList->itemModel()->index(i, 0);

		if(dynamic_cast<QNotebookListItemModel*>(ui.lwNotebookList->itemModel())->isMarked(nextRowIndex))
		{
			if(m_hEvernote->deleteNotebook(qobject_cast<QNotebookListItemModel*>(ui.lwNotebookList->itemModel())->getNotebook(nextRowIndex)) == false)
			{
				displayError(trUtf8("Unable to delete notebook"), QString(m_hEvernote->getLastErrorString().c_str()));
			}
			else
			{
				ui.lwNotebookList->itemModel()->removeRow(i);
				subSelectedCount();
			}
		}
	}

	m_hEvernote->loadNotebookList();
	setProgressIndicator(false);
	loadNotebooksIntoView();
	ui.deleteSelectedAction->setEnabled(true);


	((QvernoteView*)m_parent)->loadNotebookList();
}
